#include <iostream>
#include <string>
#include <ctime>
#include<cassert>
#include<unistd.h>
#include"Socket.hpp"
#include"Protocal.hpp"

static void Usage(const string &proc)
{
    cout<<"\nUsage"<<proc<<" serverip serverport\n"<<endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r=sockfd.Connect(serverip,serverport);
    if(!r) return 1;

    srand(time(nullptr));
    int cnt=1;
    const string opers="+-*/%=&^";
    string inbuffer_stream;
    while(cnt<=10)
    {
        cout<<"------------------"<<cnt<<"次测试"<<"--------------------"<<endl;
        int x=rand()%100+1;//通过随机数来构建请求
        int y=rand()%100;
        char oper=opers[rand()%opers.size()];
        Request req(x,y,oper);
        req.DebugPrint();//打印新请求构建完成

        string package;
        req.Serialize(&package);
        package=Encode(package);
        write(sockfd.Fd(),package.c_str(),package.size());//向服务器发送请求
        char buffer[128];
        ssize_t n=read(sockfd.Fd(),buffer,sizeof(buffer));//接收处理过的信息
        if(n>0)
        {
            buffer[n]=0;
            inbuffer_stream+=buffer;//不断获取字节流信息，有可能是完整的报文或多个或不足
            cout<<inbuffer_stream<<endl;
            string content;
            bool r=Decode(inbuffer_stream,&content);
            assert(r);

            Response resp;
            r=resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();//打印结果相应完成
        }
        cout<<"-----------------------------------------------"<<endl;
        sleep(1);
        cnt++;
    }
    sockfd.Close();
    return 0;
}